/*
 * @Author: zhengzhuang
 * @Date: 2020-05-16 15:28:15
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-01-27 09:22:49
 * @Description: In User Settings Edit
 * @FilePath: /C20Driver/lib/utils/utils.dart
 */
import 'dart:io';
// import 'package:baidu_face/baidu_face.dart';
// import 'package:baidu_face/config.dart';
// import 'package:baidu_face/enums.dart';
import 'package:flutter/material.dart';
import 'package:flutter_native_image/flutter_native_image.dart';
import 'package:image_picker/image_picker.dart';
import 'package:C20Driver/event/event_bus.dart';
import 'package:C20Driver/model/plice_model.dart';
import 'package:C20Driver/provider/driver_information.dart';
import 'package:C20Driver/routers/navigator_util.dart';
import 'package:C20Driver/service/mqtt_manage.dart';
import 'package:C20Driver/service/request.dart';
import 'package:C20Driver/service/socket_manage.dart';
import 'package:C20Driver/utils/loading.dart';
import 'package:C20Driver/utils/permission_handler.dart';
import 'package:C20Driver/utils/toast.dart';
import 'package:package_info/package_info.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';

class Utils {
  /// 获取当前app版本号
  static Future<String> getVersionNumber() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String _currentVersionCode = packageInfo.version;
    return _currentVersionCode;
  }

  /// 拨打电话号码
  static Future callPhone(number) async {
    if (await canLaunch('tel:$number')) {
      await launch('tel:$number');
    } else {
      throw 'Could not launch $number';
    }
  }

  /// 时间两位数处理
  static String twoDigitTime(int _time) {
    if (_time < 10) {
      return '0' + _time.toString();
    } else {
      return _time.toString();
    }
  }

  /// 图片上传
  static Future<String> imageUpload(BuildContext context) async {
    String imageName = '';
    var image = await ImagePicker.pickImage(
        source: ImageSource.gallery, imageQuality: 30);
    imageName = image.path;
    int leng = await image.length();
    print('lllllllllllllllll$leng');
    int qua;
    if (leng > 1000000) {
      qua = 100000000 ~/ leng;
      qua = qua < 10 ? 10 : qua;
      File compressedFile = await FlutterNativeImage.compressImage(image.path,
          quality: qua, percentage: 80);
      // print('qqqqqqqqqqqqqqqq$qua');
      // print(image.lengthSync());
      // print(compressedFile.lengthSync());
      imageName = compressedFile.path;
    }
    // File newimage = File(imageName);
    // leng = await newimage.length();
    // print('lllllllllllllllll$leng');

    //七牛上传
    // String _imagetype = 'png';
    // List type = imageName.split('.');
    // if (type.length > 1) {
    //   _imagetype = type[type.length - 1];
    // }
    // var tokendata = await Request.genUptoken(
    //     clientId: MqttManage.getInstance().getClientId, defaultFix: _imagetype);
    // var data = tokendata['tokenList'][0];
    // String resourceKey = data['resourceKey'];
    // String token = data['token'];
    // Map qiniudata = await Request.qiniuUpload(
    //     key: resourceKey, uploadToken: token, file: imageName);
    // String imageurl = qiniudata['url'];
    // return imageurl;

    //普通上传
    Loading.showLoading(context);
    return Request.uploadImg(imageName).then((res) {
      NavigatorUtil.goBack(context);
      ToastX.center('图片上传成功');
      return res;
    });
  }

  /// 扫脸认证
  static void setFaceRecognition(BuildContext context) async {
    // DriverInformation provider =
    //     Provider.of<DriverInformation>(context, listen: false);
    // await provider.setThresholdAndface();
    // if (provider.needFace == '0000') {
    // final config = Config(
    //   livenessTypeList: [LivenessType.Eye],
    // );
    // if (Platform.isAndroid) {
    //   await BaiduFace.instance.init('driver-01-face-android', config: config);
    // } else if (Platform.isIOS) {
    //   await BaiduFace.instance.init('driver-03-face-ios', config: config);
    // }
    // final base64Image = await BaiduFace.instance.liveDetect();
    // var data = await Request.submitFaceRecognition(base64Image,
    //     provider.driverInfo.idNo, provider.driverInfo.driverName, '0');
    // if (data['error_msg'] == 'SUCCESS') {
    //   PliceModel mod = PliceModel.fromJson(data);
    //   if (mod.result.score >= double.parse(provider.threshold)) {
    //     print('人脸识别成功----1111111');
    //     setWorkimgStatus(context);
    //     print('人脸识别成功----2222222');
    // BaiduFace.instance.uninitCollect();
    // } else {
    //   ToastX.center('人脸识别失败，相似度太低');
    // }
    // } else {
    //   ToastX.center('人脸识别失败');
    // }

    // } else {
    setWorkimgStatus(context);
    // }
  }

  /// 修改出车状态
  /// orderState: 1 ==> 没有订单， 2 ===> 订单进行中
  static void setWorkimgStatus(BuildContext context) async {
    DriverInformation provider =
        Provider.of<DriverInformation>(context, listen: false);

    print('wwwwwwwwwwwwwww----------${provider.driverInfo.workingStatus}');
    if (await PermissionHandlerX.position(context)) {
      switch (provider.driverInfo.workingStatus) {
        // 接单状态(出车状态) 0010:暂停 0020:出车(开始接单) 0030:收车  0040:行程中
        case '0030': // 收车中，开始出车
          // MqttManage.getInstance().driverOnline(context, "on");
          provider.setDriverInformation(workingStatus: '0020');
          break;
        case '0010': // 暂停中，开始出车
          // MqttManage.getInstance().driverOnline(context, "on");
          provider.setDriverInformation(workingStatus: '0020');
          break;
        case '0020': // 出车中，开始收车
          // Request.closeReceivingOrder(context);
          provider.setDriverInformation(workingStatus: '0030');
          break;
        case '0040': // 订单进行中
          Utils.jumpCurrentOrder(context);
          break;
        default:
      }
    }
  }

  /// 订单跳转
  static void jumpCurrentOrder(context) {
    // UserrealtimeorderProvide provider = Provider.of<UserrealtimeorderProvide>(context, listen: false);
    // switch (provider.transferStatus) {
    //   case 0: // 为去接乘客
    //     provider.setTransferStatus(0);
    //     NavigatorUtil.jump(context, '/pickUpPassengers');
    //     break;
    //   case 1: // 为到达约定地点
    //     NavigatorUtil.jump(context, '/pickUpPassengers');
    //     break;
    //   case 2: // 还未到达目的地
    //     NavigatorUtil.jump(context, '/pickUpPassengers');
    //     break;
    //   default:
    // }
  }

  /// 输入经纬度打开地图
  static void openGaode(
      {String lat, String lng, String name, BuildContext context}) async {
    print('输入经纬度打开地图');
    print(lat);
    print(lng);
    print(name);
    var url = '';
    if (Platform.isIOS) {
      //ios相关代码
      url = 'iosamap://navi?sourceApplication=appName' +
          '&lat=' +
          '$lat' +
          '&lon=' +
          '$lng' +
          '&dev=1&style=2';
    } else if (Platform.isAndroid) {
      url = 'androidamap://viewMap?poiname=' +
          '$name' +
          '&lat=' +
          '$lat' +
          '&lon=' +
          '$lng' +
          '&dev=0';
    }
    if (await canLaunch(url) != null) {
      await launch(url);
    } else {
      showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('无法打开高德地图'),
              content: Text('请下载高德地图'),
              actions: <Widget>[
                FlatButton(
                  child: Text('确定'),
                  onPressed: () {
                    Navigator.pop(context);
                  },
                ),
              ],
            );
          });
      throw 'Could not launch $url';
    }
  }

  /// 监听进行中点击返回按钮
  static Future<void> orderGoHome(BuildContext context) {
    return showDialog(
        context: context,
        builder: (_) => AlertDialog(
                title: Text("订单进行中"),
                content: Text("确定要返回吗"),
                actions: <Widget>[
                  FlatButton(
                    child: Text("确定退出"),
                    onPressed: () {
                      SocketManage().stopSocket(context);
                      Navigator.of(context).pop();
                      eventBus.fire(new SetDispatchOrderList());
                      Navigator.of(context)
                          .popUntil(ModalRoute.withName("/indexPage"));
                      return true;
                    },
                  ),
                  FlatButton(
                    child: Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      return false;
                    },
                  ),
                ]));
  }

  static getDeviceMediaInfoWidth(BuildContext context) {
    //屏幕大小
    Size mSize = MediaQuery.of(context).size;
    //密度
    double mRatio = MediaQuery.of(context).devicePixelRatio;
    //设备像素
    double width = mSize.width * mRatio;
    double height = mSize.height * mRatio;

    return width;
  }
}
